package com.ruoyi.system.service.report.Impl;

import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.TempleLib;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.rtf.RtfToZh;
import com.ruoyi.system.domain.report.vo.*;
import com.ruoyi.system.mapper.report.TeacherMapper;
import com.ruoyi.system.service.report.ITeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ITeacherServiceImpl  implements ITeacherService {

    @Autowired
    private TeacherMapper teacherMapper;

    /**
     * 条件分页查询
     *
     * @param
     */
    @Override
    public TabPtdetailTailPatientTotalVO getList(TabPtdetailTailPatientVO tabPtdetailTailPatientVO) {
        List<TabPtdetailTailPatientVO> list = teacherMapper.getPydetailList(tabPtdetailTailPatientVO);
        TabPtdetailTailPatientTotalVO tabPtdetailTailPatientTotalVO = new TabPtdetailTailPatientTotalVO();

        tabPtdetailTailPatientTotalVO.setTotal(teacherMapper.totalCount(tabPtdetailTailPatientVO));
        tabPtdetailTailPatientTotalVO.setTabPtdetailTailPatientVO(list);
        return tabPtdetailTailPatientTotalVO;
    }

    /**
     * 下拉检查项目
     * @return
     */
    @Override
    public List<String> getDropDownCheckName() {
        return teacherMapper.getDropDownCheckName();
    }

    /**
     * 下拉检查状态
     *
     * @return
     */
    @Override
    public List<StatusVo> getDropDownState() {
        return teacherMapper.getDropDownState();
    }

    /**
     * 随访信息查询
     *
     * @param ptdeId
     * @return
     */
    @Override
    public SurveyVo getSurvey(String ptdeId) {
        return teacherMapper.getSurvey(ptdeId);
    }

    /**
     * 查询病史
     * @param
     * @return
     */
    @Override
    public PtDetailBgReadyVo getBgReadyTxt(String ptdeId,String userName,String reportId) {
            return teacherMapper.getBgReadyTxt(ptdeId);
    }

    /**
     * 检查意见
     *
     * @param patientId
     * @return
     */
    @Override
    public PtCheckOpinionVo ptdtCheckyjTxt(String patientId) {
        return teacherMapper.ptdtCheckyjTxt(patientId);
    }

    /**
     * 检查所见
     *
     * @param patientId
     * @return
     */
    @Override
    public PtDetailCheckSeeTxtVo ptdtCheckSjTxt(String patientId) {
        return teacherMapper.ptdtCheckSjTxt(patientId);
    }

    /**
     * 学生患者查询
     *
     * @param
     * @return
     */
    @Override
    public PtPatientVo getPatient(String ptdeId) {
        PtPatientVo patient = teacherMapper.getPatient(ptdeId);
        return patient;
    }

    /**
     * 修改患者信息
     * @param ptPatientVo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    @Override
    public void updatePatient(PtPatientVo ptPatientVo) {
        System.out.println(ptPatientVo);
        teacherMapper.updatePtdetail(ptPatientVo);
        teacherMapper.updatePatient(ptPatientVo);
    }

    /**
     * 获取历史记录
     * @param
     * @return
     */
    @Override
    public List<HistoryVo> getHistory(String patientId, String ptdeId) {
        List<HistoryVo> list = teacherMapper.getHistory(patientId,ptdeId);
        return list;
    }

    /**
     * 获取病人 随访,病史,检查所见,检查意见
     * @param
     * @return
     */
    @Override
    public HistoryVo getPatientReportInfo(String ptdeId) {
        return teacherMapper.getPatientReportInfo(ptdeId);
    }

    /**
     * 序列
     * @param
     * @return
     */
    @Override
    public List<StudiesSeriesVo>  getStudiesSeries(String checkCode) {
        return teacherMapper.getStudiesSeries(checkCode);
    }

    /**
     * 查询模板树
     * @return
     */
    @Override
    public HashMap<String, List<TreeSelect>> getTemplate(Long userId) {
        List<TempleLib> list = teacherMapper.getTempleTree(userId);
        List<TempleLib> depts = templeLibTree(list);
        List<TreeSelect> collect = depts.stream().map(TreeSelect::new).collect(Collectors.toList());
       HashMap<String, List<TreeSelect>> stringArrayListHashMap = new HashMap<>();
       stringArrayListHashMap.put("public",collect);
       return stringArrayListHashMap;
    }

    /**
     * 检查意见,检查所见模板
     * @param id
     * @param parentId
     * @return
     */
    @Override
    public TemplateInfo templateInfo(String id, String parentId) {
        TemplateInfo templateInfo = teacherMapper.getTemplateInfo(id, parentId);
        if (templateInfo != null){
            try {
                templateInfo.setLibCheckSj(RtfToZh.parseRtf(templateInfo.getLibCheckSj()));
                templateInfo.setLibCheckYj(RtfToZh.parseRtf(templateInfo.getLibCheckYj()));
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
            return templateInfo;
        }
        return null;
    }


    /**
     * 获取当前用户管理的所有班级
     * @param userName
     * @return
     */
    @Override
    public List<ClassLIstVo> getClassList(String userName) {
        //校验当前用户是否为教师
//        if(){
//
//        }
        return teacherMapper.getClassList(userName);
    }

    /**
     * 获取当前用户拥有班级的所有学生
     * @param
     * @param classZ
     * @return
     */
    @Override
    public List<ClassStudentListResVo> getClassStudentList(String classZ) {
        return teacherMapper.getClassStudentList(classZ);
    }

    /**
     * 发布患者报告
     * @param
     * @param
     */
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    @Override
    public void addRelease(List<ClassStudentListVo> list,String teacherUserName) {
        teacherMapper.addReport(list,teacherUserName);
    }

    /**
     * 教师查询患者报告
     * @param studentReportReqVo
     * @param
     * @return
     */
    @Override
    public List<StudentReportListPageResVo> getStudentReportListPage(StudentReportReqVo studentReportReqVo, String userName) {

        return teacherMapper.getStudentReportListPage(userName,studentReportReqVo);
    }

    /**
     * 评价,评分
     * @param commentScoreReqVo
     */
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    @Override
    public void addCommentScore(CommentScoreReqVo commentScoreReqVo,String status) {
        teacherMapper.addCommentScore(commentScoreReqVo);
        teacherMapper.updateReport(commentScoreReqVo,status);
        try {
        } catch (Exception e) {
            throw new GlobalException("新增评价失败,请联系管理员");
        }
    }

    /**
     * 修改评价
     * @param commentScoreReqVo
     */
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    @Override
    public void updateCommentScore(CommentScoreReqVo commentScoreReqVo) {
        teacherMapper.updateCommentScore(commentScoreReqVo);
        teacherMapper.updateReport(commentScoreReqVo,"2");
        try {
        } catch (Exception e) {
            throw new GlobalException("更新评价失败,请联系管理员");
        }

    }

    @Override
    public  List<String> getCompleteStatus() {
        List<String> completeStatus = teacherMapper.getCompleteStatus();
        return completeStatus;
    }

    @Override
    public CommentReportResVo getReportComment(String reportId) {
        return teacherMapper.getReportComment(reportId);
    }


    @Override
    public List<DICOMSeriesImgVo> getStudyInsta(String studyInsta) {
        return teacherMapper.getStudyInsta(studyInsta);
    }

    private List<TempleLib> templeLibTree(List<TempleLib> depts)
    {
        List<TempleLib> returnList = new ArrayList<TempleLib>();
        List<Long> tempList = new ArrayList<Long>();
        for (TempleLib dept : depts)
        {
            tempList.add(dept.getId());
        }
        for (Iterator<TempleLib> iterator = depts.iterator(); iterator.hasNext();)
        {
            TempleLib dept = (TempleLib) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getLibParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    private void recursionFn(List<TempleLib> list, TempleLib t)
    {
        // 得到子节点列表
        List<TempleLib> childList = getChildList(list, t);
        t.setChildren(childList);
        for (TempleLib tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    private List<TempleLib> getChildList(List<TempleLib> list, TempleLib t)
    {
        List<TempleLib> tlist = new ArrayList<TempleLib>();
        Iterator<TempleLib> it = list.iterator();
        while (it.hasNext())
        {
            TempleLib n = (TempleLib) it.next();
            if (StringUtils.isNotNull(n.getLibParentId()) && n.getLibParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    private boolean hasChild(List<TempleLib> list, TempleLib t)
    {
        return getChildList(list, t).size() > 0;
    }

}
